<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/25
 * Time: 15:53
 */

namespace App\Service\Core\Admin\Role;

use App\Model\Core\Admin\AdminUserRoleModel;
use App\Service\Core\CoreBaseService;
use App\Traits\ModelStoreTrait;

/**
 * @method $this setName($val)
 * @method $this setStatus($val)
 * @method $this setSortOrder($val)
 * @method $this setRemark($val)
 * @package App\Service\Core\Sys\User\Role
 */
class AdminUserRoleStoreService extends CoreBaseService
{
    use ModelStoreTrait;

    private array $required_param = ['name'];

    public function store($role_id = 0): array
    {
        $this->check_required_param($this->required_param);
        if (!empty($this->errors)) {
            return alert_info(1, $this->errors[0], $this->errors);
        }
        $name = $this->getParam('name');
        $status = $this->getParam('status');
        $sort_order = $this->getParam('sort_order');
        $remark = $this->getParam('remark');

        $check = AdminUserRoleModel::getInstance()->checkName($name, $role_id);
        if (!empty($check)) {
            return alert_info(1, '角色名称已存在');
        }
        $data = [
            'name' => $name,
            'status' => $status,
            'sort_order' => $sort_order,
            'remark' => $remark,
        ];
        if ($role_id) {
            $role_info = AdminUserRoleModel::getInstance()->getOne($role_id);
            if (empty($role_info)) {
                return alert_info(1, '编辑角色不存在');
            }
            $change_data = easy_check_change_data($role_info, $data);
            if (empty($change_data)) {
                return alert_info(0, '信息没有变化');
            }
            $data['updated_at'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $this->operate_by;
            $res = AdminUserRoleModel::getInstance()->updateOne($role_id, $data);
            $this->addLog('角色管理', '修改角色【' . $role_id . '】', $this->operate_id, $this->operate_by);
        } else {
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['created_by'] = $this->operate_by;
            $data['updated_at'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $this->operate_by;
            $res = AdminUserRoleModel::getInstance()->addOne($data);
            $role_id = $res;
            $this->addLog('角色管理', '添加角色【' . $role_id . '】', $this->operate_id, $this->operate_by);
        }
        if ($res === false) {
            return alert_info(1, '操作失败：数据库繁忙');
        }
        return alert_info(0, '操作成功', ['role_id' => $role_id]);
    }
}
